/*************************************************************************************************************
  Copyright (c) 2010, Zack Evans
  All rights reserved.

  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of CapriSoft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
**************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ComponentModel;
using System.Text;

namespace Extention
{
    public class ReflectHelper
    {
        /// <summary>
        /// Read the column "or property" names that have been marked with the custom ReadableProperty Attribute
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public static List<string> ReadColumns(object T)
        {
            List<PropertyInfo> objects =
                (List<PropertyInfo>)(from a in T.GetType().GetProperties() where a.GetCustomAttributes(typeof(ReadableProperty), true).Count() > 0 select a).ToList();

            return (List<string>)(from query in objects select query.Name).ToList();
        }
        public static Dictionary<string,Type> ReadType(Type type)
        {
            PropertyInfo[] properties =
                type.GetProperties();
            
            object[] customAttributes =
                type.GetCustomAttributes(typeof(ReadableProperty), true);

            List<String> customAttributeName =
                (from a in customAttributes select ((ReadableProperty)a).Name).ToList();

            Dictionary<string, Type> _propertyInfo = new Dictionary<string, Type>();

            if (customAttributes.Count() > 0)
            {
                List<string> propertyList = (from a in properties where customAttributeName.Contains(a.Name) select a.Name).ToList();
                foreach (string propertyName in propertyList)
                    _propertyInfo.Add(propertyName, GetDataType(type, propertyName));
            }

            return _propertyInfo;
        }
        public static Dictionary<string, Type> ReadTypeOnly(Type type)
        {
            PropertyInfo[] properties =
                type.GetProperties();

            object[] customAttributes =
                type.GetCustomAttributes(typeof(ReadableProperty), true);

            List<String> customAttributeName =
                (from a in customAttributes select ((ReadableProperty)a).Name).ToList();

            Dictionary<string, Type> _propertyInfo = new Dictionary<string, Type>();

            if (properties.Count() > 0)
            {
                List<string> propertyList = (from a in properties select a.Name).ToList();
                foreach (string propertyName in propertyList)
                {
                    foreach(PropertyInfo p in properties)
                        if(p.Name == propertyName)
                            _propertyInfo.Add(propertyName, p.PropertyType);
                }
            }

            return _propertyInfo;
        }
        public static bool IsPrimaryKey(Type type, string PropertyName)
        {
            List<PropertyInfo> properties =
                (from a in type.GetProperties() where a.Name == PropertyName select a).ToList();

            List<object> customAttributes = new List<object>(
                (from a in type.GetCustomAttributes(typeof(ReadableProperty), true) select a).ToList());

            ReadableProperty readableProperty =
               (ReadableProperty)(from a in customAttributes
                              where ((ReadableProperty)a).Name == PropertyName
                              select a).ToList().First();

            if (readableProperty != null)
                return readableProperty.IsPrimaryKey;
            else return false;
        }
        public static object ReadData(object T, string PropertyName)
        {
            if (T == null)
                return null;

            if (String.IsNullOrEmpty(PropertyName))
                throw new ArgumentNullException("PropertyName argument may not be null or empty");

            PropertyDescriptorCollection collection =
                TypeDescriptor.GetProperties(T);

            PropertyDescriptor desc =
                collection[PropertyName];

            if (desc != null)
                return desc.GetValue(T);

            else throw new ApplicationException("property not found in object");
        }
        public static Type GetDataType(object T, string PropertyName)
        {
            PropertyDescriptorCollection collection =
                TypeDescriptor.GetProperties(T);

            PropertyDescriptor desc =
                collection[PropertyName];

            if (desc != null)
                return desc.GetValue(T).GetType();

            else throw new ApplicationException("property not found in object");
        }
        public static Type GetDataType(string typeName)
        {
            switch (typeName.ToLower())
            {
                case "int":
                    {
                        return typeof(Int32);
                    }
                case "bigint":
                    {
                        return typeof(Int64);
                    }
                case "smallint":
                    {
                        return typeof(Int16);
                    }
                case "varchar":
                    {
                        return typeof(string);
                    }
                case "char":
                    {
                        return typeof(string);
                    }
                case "bit":
                    {
                        return typeof(bool);
                    }
                case "datetime":
                    {
                        return typeof(DateTime);
                    }
                case "smalldatetime":
                    {
                        return typeof(DateTime);
                    }
                case "timestamp":
                    {
                        return typeof(DateTime);
                    }
                case "double":
                    {
                        return typeof(double);
                    }
                case "numeric":
                    {
                        return typeof(double);
                    }
                case "float":
                    {
                        return typeof(float);
                    }
                default:
                    return Type.GetType(String.Format("System.{0}", typeName));
            }
        }
        public static string GetStringDataType(Type type)
        {
            return type.Name;
        }

        public static string SimpleCode(Type type)
        {
            StringBuilder _code = new StringBuilder();

            //simple check for our supported modifiers
            if(type.IsPublic)
                _code.Append("public ");
            else _code.Append("private ");

            //simple check for our supported types
            if (type.IsClass)
                _code.Append("class ");
            else _code.Append("interface ");

            _code.Append(type.Name + " ");

            _code = 
                AddInheritance(_code, type);

            _code =
                AddProperties(_code, type);

            _code =
                AddConstructor(_code, type);

            _code.Append("}");

            return _code.ToString();
        }
        private static StringBuilder AddConstructor(StringBuilder _code, Type type)
        {
            ConstructorInfo[] constructors =
                   type.GetConstructors();

            foreach (ConstructorInfo info in constructors)
            {
                string declaringType = GetStringDataType(info.DeclaringType);
                string typeName = info.Name;
                
                _code.AppendLine();

                if (info.IsPublic)
                    _code.Append("   public ");
                else _code.Append("   private ");

                _code.Append(String.Format("{0}()", declaringType));
                _code.AppendLine();
                _code.Append("   {");
                _code.AppendLine();
                _code.Append("       //add your constructor information here");
                _code.AppendLine();
                _code.Append("   }");
                _code.AppendLine();
            }
            return _code;
        }
        private static StringBuilder AddInheritance(StringBuilder _code, Type type)
        {
            if(!type.BaseType.Equals(typeof(object)))
            {
                _code.Append(": ");

                _code.Append(String.Format("{0}",type.BaseType.Name));
                _code.AppendLine();
                _code.Append("{");
                _code.AppendLine(); 
            }

            return _code;
        }
        private static StringBuilder AddProperties(StringBuilder _code, Type type)
        {
            PropertyInfo[] properties =
                    type.GetProperties();

            foreach (PropertyInfo info in properties)
            {
                _code.Append("   public ");
                _code.Append(info.PropertyType.Name + " " + info.Name + "{ get; set;}");
                _code.AppendLine();
            }
            return _code;
        }
    }
}
